using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using MVCDemosoft.Models;
using MVCDemosoft.Repository;
using MVCDemosoft.Request;
namespace MVCDemosoft.Controllers
{
    public class CrudController : Controller
    {
        public IActionResult Indexview()
        {
            var cate = new EfRepository<Categroy>();
            var cate1 = cate.Table.FirstOrDefault();
            if (cate1 == null)
            {
                cate.Insert(new Categroy
                {
                    CategroyName = "供给商"
                });
            }
            var pro = new EfRepository<Product>();
            var pro1 = pro.Table.Where(x => x.isDeleted == false).ToList();
            return View(pro1);
        }
        public IActionResult CreateOrEdit(int id)
        {
            var pro = new EfRepository<Product>();
            var pro1 = pro.Table.Where(x => x.Id == id).FirstOrDefault();
            return View(pro1);
        }
        public IActionResult Save(Accounts model)
        {
            var pro = new EfRepository<Product>();
            if (model.id > 0)
            {
                var pro1 = pro.GetById(model.id);
                if (pro1 != null)
                {
                    pro1.ProductName = model.productname;
                    pro1.Supplier = model.Supplier;
                    pro1.Price = model.price;
                    pro1.Stock = model.stock;
                    pro1.Remarks = model.remarks;
                    pro.Update(pro1);
                }
            }
            else
            {
                pro.Insert(new Product
                {
                    ProductName = model.productname,
                    Supplier = model.Supplier,
                    Price = model.price,
                    Stock = model.stock,
                    Remarks = model.remarks,
                    CategroyId = 1,
                });
            }
            return Ok();
        }
        public IActionResult Query(Query request)
        {
            var pro = new EfRepository<Product>();
            List<Product> pro1;
            if(request != null && request.keyword != null && request.keyword.Length > 0){
                pro1 = pro.Table.Where( x => x.isDeleted == false && ( x.ProductName.Contains(request.keyword)||x.Remarks.Contains(request.keyword))).ToList();
            }else{
                pro1 = pro.Table.Where( x => x.isDeleted == false).ToList();
            }

            return Json(pro1);
        }
        public IActionResult Deleted(int id)
        {
            var pro = new EfRepository<Product>();
            pro.Deleted(id);
            return RedirectToAction("indexview");
        }
    }
}